Add Two Numbers

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8

Solution:

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. public class Solution {
  10. public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
  11. ListNode f = new ListNode(0);
  12. ListNode p = f;
  13. int c = 0;
  14. while (l1 != null || l2 != null || c != 0) {
  15. int a = (l1 == null) ? 0 : l1.val;
  16. int b = (l2 == null) ? 0 : l2.val;
  17. int s = a + b + c;
  18. p.next = new ListNode(s % 10);
  19. p = p.next;
  20. if (l1 != null) l1 = l1.next;
  21. if (l2 != null) l2 = l2.next;
  22. c = s / 10;
  23. }
  24. return f.next;
  25. }
  26. }